package com.marketingexpert.controller.personmgnt;

import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONArray;

import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.Controller;

import com.marketingexpert.domain.User;
import com.marketingexpert.domain.UserType;
import com.marketingexpert.service.snsmgnt.SnsService;
import com.marketingexpert.service.snsmgnt.SnsServiceFactory;
import com.marketingexpert.service.usermgnt.UserService;

public class GetSinaWeiboAccountController implements Controller {

private String successView = null;
	
	private UserService userService = null;
	
	private SnsServiceFactory snsServiceFactory;	
	
	public ModelAndView handleRequest(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		
		response.setContentType("application/x-json;charset=GBK"); 
		response.setHeader("Pragma", "No-cache"); 
		response.setHeader("Cache-Control", "no-cache"); 
		response.setHeader("Cache-Control", "no-store"); 
		response.setDateHeader("Expires", 0);  
		
		String parentUserId = (String)request.getSession().getAttribute("parentUserId");
		
		List<User> snsUsers = userService.queryUserByParentId(parentUserId);
		
		List<com.marketingexpert.service.snsmgnt.User> weiboUsers = new ArrayList<com.marketingexpert.service.snsmgnt.User>();
		
		
		
		SnsService snsService = getSnsServiceFactory().getService(SnsServiceFactory.SINA);
		
		//Map<String,String> accounts = new HashMap<String, String>();
		
		for(Iterator<User>it = snsUsers.iterator();it.hasNext();) {
			User myUser = it.next();
			
			if(myUser.getUserType().equals(UserType.TENCENTWEIBO)) {
				continue;
			}
			
			com.marketingexpert.service.snsmgnt.User weiboUser = snsService.getUserDetails(myUser.getAccessToken(), myUser.getSecret(), myUser.getUserId());
			weiboUsers.add(weiboUser);
		}
		
		PrintWriter out = response.getWriter(); 
		JSONArray jsonListd = JSONArray.fromObject(weiboUsers); 
		out.print(jsonListd);
		return null;
	}

	public String getSuccessView() {
		return successView;
	}

	public void setSuccessView(String successView) {
		this.successView = successView;
	}

	public UserService getUserService() {
		return userService;
	}

	public void setUserService(UserService userService) {
		this.userService = userService;
	}

	public SnsServiceFactory getSnsServiceFactory() {
		return snsServiceFactory;
	}

	public void setSnsServiceFactory(SnsServiceFactory snsServiceFactory) {
		this.snsServiceFactory = snsServiceFactory;
	}

	
	
	
}
